package at.main.util;
import at.main.android.RecordStore;

public class MyRecordStore
{
	private RecordStore m_ms = null;
	private String m_REC_STORE;
	
	public MyRecordStore (String db_name)
	{
		m_REC_STORE = db_name;
	}
	public MyRecordStore(){
		m_REC_STORE = "db_PacMan";
	}
	public void openRecStore()
	{
		try
		{
			// The second parameter indicates that the record store should be created if it does not exist
			m_ms = RecordStore.openRecordStore(m_REC_STORE, true );			
		}
		catch (Exception e)
		{			
			db(e.toString());
		}
	}

	public void closeRecStore()
	{
		try
		{
			m_ms.closeRecordStore();
		}
		catch (Exception e)
		{
			db(e.toString());
		}
	}
	// TODO: deleteRecStore
	public void deleteRecStore()
	{
		if (RecordStore.listRecordStores() != null)
		{
			try
			{
				RecordStore.deleteRecordStore(m_REC_STORE);
			}
			catch (Exception e)
			{
				db(e.toString());
			}
		}
	}
	
	//TODO: Apend or change exist Record
	public void writeRecord(String str)
	{
		byte[] rec = str.getBytes();
		try
		{
			if(m_ms.getNumRecords() == 0)
			{
				m_ms.addRecord(rec, 0, rec.length);
			}
			else
				m_ms.setRecord(1,rec,0,rec.length);
		}
		catch (Exception e)
		{
			db(e.toString());
		}
	}
	
	// TODO: read Records
	public String readRecord()
	{
		try
		{
			// Intentionally make this too small to test code below
			byte[] recData = null;
			int len = 0;
			
			if(m_ms.getNumRecords()==0)
				return null;		
			if (m_ms.getRecordSize(1) > 0)
				recData = new byte[m_ms.getRecordSize(1)];
			else
				return null;
		
			len = m_ms.getRecord(1, recData, 0);
			return new String(recData, 0, len);
					
		}
		catch (Exception e)
		{
			db(e.toString());
		}
		return null;
	}
	
	// TODO: Debug Error
	private void db(String str)
	{
		System.err.println("Msg: " + str);
	}
}